<template>
    <div class="planList-index yuan-container">
        <div class="filter-panel">
            <span class="planList-title">
                {{planSimulation.planName}}
            </span>
            <div class="filter-list">
                <span class="filter-tips ">颗粒库存量：
                    <span class="font-bignum c-primary">{{ zlStockNum }}</span>
                    <span>kg</span>
                </span>
                <span class="filter-tips ">记录结存量：
                    <span class="font-bignum c-primary">{{ zlStorageRecordWeight || '--' }}</span>
                    <span>kg</span>
                </span>
            </div>

        </div>
        <div class="planList-top filter-panel">
            <div class="filter-list">
                <span class="filter-tips">实际生产颗粒数量：
                    <a-input class="filter-input" suffix="kg" v-model="pageData.prodNum" @input="prodNumChange"></a-input>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips ">提取物需求量：
                    <span class="font-bignum c-primary">{{(pageData.needNum  )|| '--' }}</span>
                    <span>kg</span>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">实际投料量:
                    <span class="font-bignum c-warning">{{(pageData.touliao  )|| '--'}}</span>
                    <span>kg</span>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">预计产出时间：
                    <span class="mast-ico"></span>
                    <a-date-picker class="yuan-form-input" @change="planTimeChange($event)" placeholder="预计产出时间" v-model="pageData.planTime" valueFormat="YYYY-MM-DD" />
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">完成天数：
                    <span class="mast-ico"></span>
                    <a-input-number class="yuan-form-input" @change="finishDayChange($event)" placeholder="完成天数" v-model="pageData.finishDay"/>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">预计完成时间：
                    <span class="mast-ico"></span>
                    <a-date-picker class="yuan-form-input" placeholder="预计完成时间" v-model="pageData.finishTime" valueFormat="YYYY-MM-DD" :disabled="true" />
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">提取物状态：<span class="mast-ico"></span></span>

                <a-select v-model="pageData.jgfState" allowClear placeholder="提取物状态">
                    <a-select-option value="1">混一</a-select-option>
                    <a-select-option value="2">混二</a-select-option>
                </a-select>
            </div>
        </div>

        <div style="border-bottom:solid 1px #999;margin-bottom:20px"></div>
        <!-- <div style="font-size:16px;font-weight:bold;margin-bottom:10px">
            辅料
        </div>
        <div class="filter-panel">
            <div v-for="(item,idx) in accSelList">
                <div class="filter-list">
                    <span class="filter-tips">投入辅料：</span>
                    <a-select v-model="accSelList[idx].accId" allowClear placeholder="请选择辅料">
                        <a-select-option :value="item.id" v-for="item in accList">{{item.materialName}}</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span class="filter-tips">投入数量：</span>
                    <a-input class="filter-input" suffix="kg" v-model="accSelList[idx].inputNum"></a-input>
                </div>
                <div class="filter-list" v-if="idx===0">
                    <a-button type="primary" @click="addAcc">新增</a-button>
                </div>
                <div class="filter-list" v-if="idx!==0">
                    <a-button type="danger" @click="removeAcc(idx)">删除</a-button>
                </div>
            </div>
        </div> -->

        <div class="filter-panel" style="display:flex;align-items: center;margin-bottom:20px">
            <div class="filter-list">
                <span class="filter-tips" style="font-size:16px;font-weight:bold;">
                    {{planSimulation.materialName}} 库存现状
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips ">提取物总库存：
                    <span class="font-bignum c-primary">{{stockTotal |toDecimalNoZero }}</span>
                    <span>kg</span>
                </span>
                <span class="filter-tips ">记录结存重量：
                    <span class="font-bignum c-primary">{{totalStorageRecordWeight |toDecimalNoZero }}</span>
                    <span>kg</span>
                </span>
            </div>
        </div>
        
        <a-card>
            <a-tabs type="card"  @change="tabChange">
                <template>
                    <a-tab-pane key="收粉" :tab="`收粉库存(${sfTotal}kg)`"></a-tab-pane>
                    <a-tab-pane key="过筛" :tab="`过筛库存(${gsTotal}kg)`"></a-tab-pane>
                    <a-tab-pane key="总混一" :tab="`总混一库存(${zhyTotal}kg)`"></a-tab-pane>
                    <!-- <a-tab-pane key="总混二" :tab="`总混二库存(${zheTotal}kg)`"></a-tab-pane> -->
                </template>

            </a-tabs>

            <div>
                <div class="filter-panel">
                    <div class="filter-list">
                        <span>批号：</span>
                        <a-input-search allowClear v-model="pageParams.batch" placeholder="请输入批号" @search="resetList" />
                    </div>
                    <!-- <div class="filter-list">
                        <span>可供销售天数：</span>
                        <span class="filter-range">
                            <a-input v-model="pageParams.sellDayStart"></a-input>
                            <span class="filter-tips">~</span>
                            <a-input v-model="pageParams.sellDayEnd"></a-input>
                            <span class="filter-tips">天</span>
                        </span>
                    </div>
                    <div class="filter-list">
                        <span>质量状态：</span>
                        <a-select v-model="pageParams.qualityState" @change="resetList" allowClear placeholder="请选择质量状态">
                            <a-select-option value="1">合格</a-select-option>
                            <a-select-option value="2">不合格</a-select-option>
                        </a-select>
                    </div>
                    <div class="filter-list">
                        <span>有效期：</span>
                        <a-range-picker :mode="['month','month']" :open="monthPickShow" @panelChange="handlePanelChange"
                            v-model="billMonth" @openChange="handleOpenChange" :placeholder="['开始日期','结束日期']"
                            :format="['YYYY-MM','YYYY-MM']" />
                    </div> -->
                    <div class="filter-list">
                        <a-button type="primary" @click="getList" class="filter-list">搜索</a-button>
                    </div>
                </div>
                <div class="table">
                    <a-radio-group v-model="tableSelect" @change="pageListSelectChange" style="width:100%">
                        <a-table bordered :rowKey="(row)=>row.id" :data-source="pageList" :columns="packageColumns"
                            :pagination="false" :loading="loading">
                            <template slot="select" slot-scope="text, record, index">
                                <a-radio :value="index" :checked="record.isSelect"></a-radio>
                            </template>
                            <template slot="inputNumber" slot-scope="text, record, index">
                                <span v-if="!record.isSelect">--</span>
                                <a-input
                                    type="number"
                                    style="width:100px"
                                    placeholder="请输入数量"
                                    v-model="record['inputNumber']"
                                    @input="inputNumChange"
                                    :disabled="!record[getBalanceWeightField()] || record[getBalanceWeightField()] == 0"
                                    v-else
                                />
                            </template>
                            <template slot="qualityState" slot-scope="text, record, index">
                                <span>{{record.qualityState === "1" ? "合格" : "待检"}}</span>
                            </template>
                        </a-table>
                    </a-radio-group>
                </div>
            </div>

        </a-card>

    </div>
</template>
<script lang="ts">
import nextApi from "@/api/nextApi";
import warningApi from "@/api/warningApi";
import { toDecimalNoZero } from "@/utils";
import { ColumnGroup } from "ant-design-vue/types/table/column-group";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";

@Component({
    name: "dom",
    components: {},
})
export default class index extends Vue {
    @Prop({ default: "" }) planSimulation!: any;
    @Prop({ default: "" }) pageDetail!: any;
    // 计划表格
    packageColumns = [
        {
            align: "center",
            dataIndex: "select",
            key: "select",
            title: "",
            scopedSlots: { customRender: "select" },
        },
        {
            align: "center",
            dataIndex: "tqwBatch",
            key: "tqwBatch",
            title: "批号",
        },
        {
            align: "center",
            dataIndex: "sfInTime",
            key: "sfInTime",
            title: "生产日期",
        },
        // {
        //     align: "center",
        //     dataIndex: "validTime",
        //     key: "validTime",
        //     title: "有效期至",
        // },
        {
            align: "center",
            dataIndex: "sfRecheckTime",
            key: "sfRecheckTime",
            title: "复验期",
        },
        {
            align: "center",
            dataIndex: "sfBalanceWeight",
            key: "sfBalanceWeight",
            title: "库存数量",
            // customRender: (text: string, record: any, index: number) => toDecimalNoZero(record.surplus, 2),
        },
        {
            align: "center",
            dataIndex: "sfQualityState",
            key: "sfQualityState",
            title: "质量状态",
        },
        {
            align: "center",
            dataIndex: "inputNumber",
            key: "inputNumber",
            title: "投料量（kg）",
            scopedSlots: { customRender: "inputNumber" },
        },
        {
            align: "center",
            dataIndex: "recordWeight",
            key: "recordWeight",
            title: "记录数量",
        },
    ];
    loading = false;
    pageParams: any = {
        batch: "",
        qualityState: undefined,
        sellDayStart: "",
        sellDayEnd: "",
        startTime: "",
        endTime: "",
    };
    pagination = {
        pageSize: 999,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    pageList: any[] = [];
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    stockTotal = 0;
    totalStorageRecordWeight = 0
    sfTotal = 0
    gsTotal = 0
    zhyTotal = 0
    zheTotal = 0
    async getList() {
        this.tableSelect = "";
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getPelletStorage({
                // ...this.pageParams,
                type2:this.type,
                name:this.pageDetail.materialName,
                standard:this.pageDetail.standard,
                pageSize: this.pagination.pageSize,
                page: this.pagination.current,
                // materialName: this.planSimulation.materialName,
                // materialType: this.planSimulation.materialType,
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.list || [];

            // let stockTotal = 0;
            // this.pageList.forEach((item) => {
            //     stockTotal += Number(item.surplus || 0);
            // });
            this.stockTotal = res.data?.total || 0;
            this.totalStorageRecordWeight = res.data?.totalStorageRecordWeight || 0
            this.sfTotal = res.data?.sfTotal || 0
            this.gsTotal = res.data?.gsTotal || 0
            this.zhyTotal = res.data?.zhyTotal || 0
            this.zheTotal = res.data?.heTotal || 0
            // 还原以前的投料信息
            const alarm = this.pageDetail;
            if (alarm.processPlanInputNewList.length > 0) {
                alarm.processPlanInputNewList.forEach((listOne) => {
                    this.pageList.forEach((item, idx) => {
                        console.info(item.id, listOne.materialId);
                        if (item.id === listOne.stockId) {
                            item.isSelect = true;
                            item["inputNumber"] = listOne.inputNum;
                            this.tableSelect = idx;
                        }
                    });
                });
                this.inputNumChange();
            }
            if(this.pageList.length == 0){
                this.$message.warning('该品种提取物暂无库存，请在半成品库存表-收粉、过筛、总混一表添加库存信息')
            }
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    billMonth = [];
    monthPickShow = false;
    handlePanelChange(value, mode) {
        if (mode[1] === "date") {
            const arr = value.map((item) => item.format("YYYY-MM"));
            this.billMonth = arr;
            this.pageParams.startTime = arr[0];
            this.pageParams.endTime = arr[1];
            this.resetList();
            this.monthPickShow = false;
        }
    }
    handleOpenChange(status) {
        if (status) {
            this.monthPickShow = true;
        } else {
            this.monthPickShow = false;
        }
    }

    tableSelect: any = "";
    pageListSelectChange() {
        const pageList = [...this.pageList];
        const type = pageList[this.tableSelect].isSelect;
        pageList.map((item) => {
            item.isSelect = false;
        });
        if (!type) {
            pageList[this.tableSelect].isSelect = true;
        }
        this.pageList = pageList;
        this.inputNumChange();
        console.log( this.pageList);
    }
    mounted() {
        console.log(this.pageDetail);
        this.pageData = {
            touliao: "",
            prodNum: this.pageDetail.prodNum,
            needNum: this.pageDetail.needNum,
            planTime: this.pageDetail.planTime || '',
            finishDay: this.pageDetail.finishDay || '',
            finishTime: this.pageDetail.finishTime || '',
            jgfState: this.pageDetail.jgfState,
        };
        this.getNeedNum();
        this.getList();
        this.getAccList();
        this.getTotalPelletStorage()
    }
    zlStockNum = 0
    zlStorageRecordWeight = 0
    async getTotalPelletStorage(){
        let params = {
            name:this.pageDetail.prodName,
            standard:this.pageDetail.standard,
            type:'制粒'
        }
        const res = await nextApi.getStorageOfhalfRaw(params)
        this.zlStockNum = res.data?.zlStockNum || 0
        this.zlStorageRecordWeight = res.data?.zlStorageRecordWeight || 0
    }
    pageData: any = {
        touliao: "",
        prodNum: "",
        needNum: "",
    };
    simulationTimer: number | null = null;
    inputNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        if (this.tableSelect === "") return;
        this.simulationTimer = setTimeout(async () => {
            let total = Number(this.pageList[this.tableSelect]["inputNumber"]) || 0;
            if (total > this.pageList[this.tableSelect].surplus) {
                this.$message.error("投料数量不能大于库存量");
                return;
            }
            this.pageData.touliao = toDecimalNoZero(total);
        }, 500);
    }
    prodNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            this.getNeedNum();
        }, 500);
    }
    async getNeedNum() {
        try {
            this.loading = true;
            const res = await warningApi.getNeedNum({
                id: this.pageDetail.prodId,
                need: this.pageData.prodNum,
            });
            this.pageData.needNum = res.data;
        } finally {
            this.loading = false;
        }
    }

    accSelList: any[] = [{ inputNum: "", accId: "" }];
    accList: any[] = [];
    async getAccList() {
        this.accList = [];
        try {
            this.loading = true;
            const res = await warningApi.materialStockList({
                pageSize: 999,
                page: 1,
                materialType: "辅料",
            });
            this.accList = res.data?.records || [];

            // 还原以前的投料信息
            const alarm = this.pageDetail;
            if (alarm.processPlanInputList.length > 0) {
                let accSelList: any[] = [];
                alarm.processPlanInputList.forEach((listOne) => {
                    this.accList.forEach((item, idx) => {
                        if (item.id === listOne.materialId) {
                            item["inputNum"] = listOne.inputNum;
                            item.accId = item.id;
                            accSelList.push(item);
                        }
                    });
                });
                if (accSelList.length === 0) accSelList = [{}];
                this.accSelList = JSON.parse(JSON.stringify(accSelList));
                this.inputNumChange();
            }
        } finally {
            this.loading = false;
        }
    }
    addAcc() {
        this.accSelList.push({});
    }
    removeAcc(idx) {
        this.accSelList.splice(idx, 1);
    }

    getPageInfo() {
        console.log(this.pageData);
        
        if (!this.pageData.finishTime) {
            this.$message.error("请选择制剂计划预计完成时间");
            return false;
        }
        const processPlanInputList: any[] = [];
        let total = 0;

        const item = this.pageList[this.tableSelect];
        if (!item) {
            this.$message.error("制剂计划还没有选择投料");
            return false;
        }
        total = Number(item["inputNumber"]) || 0;

        if (total > item.surplus) {
            this.$message.error("制剂计划投料数量不能大于库存量");
            return false;
        }

        // 投料
        processPlanInputList.push({
            isPro: true,
            stockId: item.id,
            batch: item.tqwBatch,
            inputNum: item.inputNumber,
            type:'提取物',
            inputName:item.tqwName,
            typeTwo:this.type,
            productDate:this.type=="收粉"?item.sfInTime:this.type=="过筛"?item.gsInTime:this.type=="总混一"?item.zhyInTime:this.type=="总混二"?item.zheInTime:item.sfInTime,
            recheckDate:this.type=="收粉"?item.sfRecheckTime:this.type=="过筛"?item.gsRecheckTime:this.type=="总混一"?item.zhyRecheckTime:this.type=="总混二"?item.zheRecheckTime:item.sfRecheckTime,
            qualityState:this.type=="收粉"?item.sfQualityState:this.type=="过筛"?item.gsQualityState:this.type=="总混一"?item.zhyQualityState:this.type=="总混二"?item.zheQualityState:item.sfQualityState,
            storageNum:this.type=="收粉"?item.sfBalanceWeight:this.type=="过筛"?item.gsBalanceWeight:this.type=="总混一"?item.zhyBalanceWeight:this.type=="总混二"?item.zheBalanceWeight:item.sfBalanceWeight,
            materialName: item.materialName,
            materialType: item.materialType,
            materialId: item.materialId,
        });

        // 辅料
        this.accSelList.forEach((item) => {
            if (item.inputNum > 0) {
                const findOne = this.accList.find((one) => {
                    return one.id === item.accId;
                });
                if (findOne) {
                    processPlanInputList.push({
                        inputNum: item.inputNum,
                        materialName: findOne.materialName,
                        materialType: findOne.materialType,
                        materialId: findOne.id,
                    });
                }
            }
        });

        return [
            {
                ...this.pageDetail,
                isPro: true,
                processPlanInputNewList:processPlanInputList,
                finishTime: this.pageData.finishTime,
                planTime: this.pageData.planTime,
                finishDay: this.pageData.finishDay,
                jgfState: this.pageData.jgfState,
                needNum: this.pageData.needNum,
                prodNum: this.pageData.prodNum,
                inputNum: total,
            },
        ];
    }
    type = '收粉'
    tabChange(e: string) {
        this.type = e
        if(this.type === '收粉'){
            this.packageColumns[2].key = 'sfInTime'
            this.packageColumns[2].dataIndex = 'sfInTime'
            this.packageColumns[3].key = 'sfRecheckTime'
            this.packageColumns[3].dataIndex = 'sfRecheckTime'
            this.packageColumns[4].key = 'sfBalanceWeight'
            this.packageColumns[4].dataIndex = 'sfBalanceWeight'
            this.packageColumns[5].key = 'sfQualityState'
            this.packageColumns[5].dataIndex = 'sfQualityState'
        }else if(this.type === '过筛'){
            this.packageColumns[2].key = 'gsInTime'
            this.packageColumns[2].dataIndex = 'gsInTime'
            this.packageColumns[3].key = 'gsRecheckTime'
            this.packageColumns[3].dataIndex = 'gsRecheckTime'
            this.packageColumns[4].key = 'gsBalanceWeight'
            this.packageColumns[4].dataIndex = 'gsBalanceWeight'
            this.packageColumns[5].key = 'gsQualityState'
            this.packageColumns[5].dataIndex = 'gsQualityState'
        }else if(this.type === '总混一'){
            this.packageColumns[2].key = 'zhyInTime'
            this.packageColumns[2].dataIndex = 'zhyInTime'
            this.packageColumns[3].key = 'zhyRecheckTime'
            this.packageColumns[3].dataIndex = 'zhyRecheckTime'
            this.packageColumns[4].key = 'zhyBalanceWeight'
            this.packageColumns[4].dataIndex = 'zhyBalanceWeight'
            this.packageColumns[5].key = 'zhyQualityState'
            this.packageColumns[5].dataIndex = 'zhyQualityState'
        }else{
            this.packageColumns[2].key = 'zheInTime'
            this.packageColumns[2].dataIndex = 'zheInTime'
            this.packageColumns[3].key = 'zheRecheckTime'
            this.packageColumns[3].dataIndex = 'zheRecheckTime'
            this.packageColumns[4].key = 'zheBalanceWeight'
            this.packageColumns[4].dataIndex = 'zheBalanceWeight'
            this.packageColumns[5].key = 'zheQualityState'
            this.packageColumns[5].dataIndex = 'zheQualityState'
        }
        this.getList()

    }
    getBalanceWeightField() {
        // 动态获取当前库存数量字段名
        return this.packageColumns[4].dataIndex;
    }
    planTimeChange(v) {
        if(v){
            let time = new Date(v).getTime()
            if(this.pageData.finishDay){
                let oneDayTimeStamp = 24*60*60*1000
                let finishTimeStamp = time + (this.pageData.finishDay*oneDayTimeStamp)
                this.pageData.finishTime = new Date(finishTimeStamp).toLocaleDateString()
            }
        }
    }
    finishDayChange(v){
        if(v){
            if(this.pageData.planTime){
                let planTimeStamp = new Date(this.pageData.planTime).getTime()
                let oneDayTimeStamp = 24*60*60*1000
                let finishTimeStamp = planTimeStamp + (v*oneDayTimeStamp)
                this.pageData.finishTime = new Date(finishTimeStamp).toLocaleDateString()
            }
        }
    }
}
</script>
<style lang="scss">
.planList-index {
    .planList-top {
        font-size: 16px;
        padding-bottom: 10px;
    }
    .planList-title {
        font-weight: bold;
        font-size: 20px;
    }

    .overview-panel {
        background-color: #fff;
        padding: 10px 10px;
    }
    .overview-title {
        margin-right: 30px;
    }
    .overview-titlebox {
        padding: 10px 0;
    }
}
</style>
